//
// Created by 刘禹晨 on 16/7/17.
// Copyright (c) 2016 yuchenliu. All rights reserved.
//

#import "SocketManager.h"
#import <CocoaAsyncSocket/GCDAsyncSocket.h>

@interface SocketManager() <GCDAsyncSocketDelegate>
{
    BOOL inited;
    NSMutableDictionary *detailDic;
    NSUserDefaults *defaults;
    NSInteger errorCount;
    NSString *state;
}
@end

@implementation SocketManager

+ (SocketManager *)instance {
    static SocketManager *_instance = nil;
    
    @synchronized (self) {
        if (_instance == nil) {
            _instance = [[self alloc] init];
        }
    }
    return _instance;
}

-(void)initSocket
{
    if(inited){
        return;
    }
    inited = TRUE;
    NSLog(@"Socket init...");
    self.socket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    defaults=[NSUserDefaults standardUserDefaults];
    self.delegate = nil;
    state = @"disconnect";
    detailDic = [NSMutableDictionary dictionary];
    NSLog(@"IP: %@",self.socketHost);
    errorCount = 0;
}

-(void)socketConnectHost{
    NSError *error = nil;
    self.socketHost = [defaults objectForKey:@"socketHost"];
    self.socketPort = (uint16_t)[defaults integerForKey:@"socketPort"];
    [self.socket connectToHost:self.socketHost onPort:self.socketPort withTimeout:15 error:&error];
    [detailDic setObject:@" " forKey:@"IP"];
    [detailDic setObject:@"Socket连接中..." forKey:@"state"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"leftMenuDataSetWiFi" object:nil userInfo:detailDic];
}

-(void)socketReConnectHost{
    NSError *error = nil;
    self.socketHost = [defaults objectForKey:@"socketHost"];
    self.socketPort = (uint16_t)[defaults integerForKey:@"socketPort"];
    [self.socket connectToHost:self.socketHost onPort:self.socketPort withTimeout:15 error:&error];
    [detailDic setObject:@" " forKey:@"IP"];
    [detailDic setObject:@"Socket重连中..." forKey:@"state"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"leftMenuDataSetWiFi" object:nil userInfo:detailDic];
}

-(void)socketDisconnect{
    if([state isEqualToString:@"disconnect"])
    {
        [detailDic setObject:@" " forKey:@"IP"];
        [detailDic setObject:@"Socket未连接" forKey:@"state"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"leftMenuDataSetWiFi" object:nil userInfo:detailDic];
    }
    [self.socket disconnect];
}

-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"Socket连接成功");
    state = @"connect";
    // 每隔30s像服务器发送心跳包
//    self.connectTimer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(longConnectToSocket) userInfo:nil repeats:YES];// 在longConnectToSocket方法中进行长连接需要向服务器发送的讯息
//    
//    [self.connectTimer fire];
    [detailDic setObject:self.socketHost forKey:@"IP"];
    [detailDic setObject:@"Socket已连接" forKey:@"state"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"leftMenuDataSetWiFi" object:nil userInfo:detailDic];
    errorCount = 0;
    [self.socket readDataWithTimeout:-1 tag:0];
    if([(id)self.delegate respondsToSelector:@selector(didSocketConnected)])
    {
        [self.delegate didSocketConnected];
    }
}

// 心跳连接
-(void)longConnectToSocket{
    
    // 根据服务器要求发送固定格式的数据，假设为指令@"longConnect"，但是一般不会是这么简单的指令
    
    NSString *longConnect = @"longConnect";
    NSData   *dataStream  = [longConnect dataUsingEncoding:NSUTF8StringEncoding];
    [self.socket writeData:dataStream withTimeout:5 tag:1];
    
}

-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    [detailDic setObject:@" " forKey:@"IP"];
    [detailDic setObject:@"Socket未连接" forKey:@"state"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"leftMenuDataSetWiFi" object:nil userInfo:detailDic];
    if (err != nil) {
        NSString *errorStr = [err.userInfo objectForKey:@"NSLocalizedDescription"];
        NSLog(@"Error: %@", errorStr);
        errorCount ++;
        if(errorCount >= 15)
        {
            errorCount = 0;
            [detailDic setObject:@" " forKey:@"IP"];
            [detailDic setObject:@"Socket连接失败" forKey:@"state"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"leftMenuDataSetWiFi" object:nil userInfo:detailDic];
        }else{
            [self socketReConnectHost];
        }
    }else{
        NSLog(@"主动断线");
    }
}

-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSLog(@"%@",data);
    if([(id)self.delegate respondsToSelector:@selector(didReadvalue:)])
    {
        [self.delegate didReadvalue:data];
    }
    [self.socket readDataWithTimeout:-1 tag:0];
}


@end